package com.example.myapplication.database

import android.content.Context
import androidx.lifecycle.LiveData

/**
 * 持仓记录仓库类
 */
class PositionRepository(context: Context) {
    
    private val positionDao = AppDatabase.getInstance(context).positionDao()
    
    /**
     * 记录买入操作
     */
    suspend fun recordBuy(
        symbol: String,
        stockName: String,
        price: Double,
        quantity: Int,
        timestamp: Long,
        reason: String? = null,
        signalStrength: Int = 0
    ): Long {
        val position = UserPosition(
            symbol = symbol,
            stockName = stockName,
            type = UserPosition.TYPE_BUY,
            price = price,
            quantity = quantity,
            timestamp = timestamp,
            reason = reason,
            signalStrength = signalStrength,
            isOpen = true
        )
        return positionDao.insert(position)
    }
    
    /**
     * 记录卖出操作（先进先出原则）
     */
    suspend fun recordSell(
        symbol: String,
        stockName: String,
        price: Double,
        quantity: Int,
        timestamp: Long,
        reason: String? = null,
        signalStrength: Int = 0
    ): Long {
        // 获取最早的未平仓买入记录
        val buyPosition = positionDao.getLatestOpenBuyPosition(symbol)
        
        // 计算盈亏
        val profit = buyPosition?.let { (price - it.price) * quantity }
        val profitRate = buyPosition?.let { (price - it.price) / it.price * 100 }
        
        // 创建卖出记录
        val sellPosition = UserPosition(
            symbol = symbol,
            stockName = stockName,
            type = UserPosition.TYPE_SELL,
            price = price,
            quantity = quantity,
            timestamp = timestamp,
            reason = reason,
            signalStrength = signalStrength,
            relatedBuyId = buyPosition?.id,
            profit = profit,
            profitRate = profitRate,
            isOpen = false
        )
        
        val sellId = positionDao.insert(sellPosition)
        
        // 更新买入记录为已平仓
        buyPosition?.let {
            val updatedBuyPosition = it.copy(isOpen = false)
            positionDao.update(updatedBuyPosition)
        }
        
        return sellId
    }
    
    /**
     * 获取所有持仓记录
     */
    fun getAllPositions(): LiveData<List<UserPosition>> {
        return positionDao.getAllPositions()
    }
    
    /**
     * 获取指定股票的持仓记录
     */
    fun getPositionsBySymbol(symbol: String): LiveData<List<UserPosition>> {
        return positionDao.getPositionsBySymbol(symbol)
    }
    
    /**
     * 获取指定股票的未平仓买入记录
     */
    suspend fun getOpenBuyPositions(symbol: String): List<UserPosition> {
        return positionDao.getOpenBuyPositions(symbol)
    }
    
    /**
     * 获取所有未平仓的持仓
     */
    fun getAllOpenPositions(): LiveData<List<UserPosition>> {
        return positionDao.getAllOpenPositions()
    }
    
    /**
     * 获取指定股票的未平仓买入数量
     */
    suspend fun getOpenBuyCount(symbol: String): Int {
        return positionDao.getOpenBuyCount(symbol)
    }
    
    /**
     * 获取指定股票的平均买入价格
     */
    suspend fun getAverageBuyPrice(symbol: String): Double? {
        return positionDao.getAverageBuyPrice(symbol)
    }
}

